//
//  FLDownloadManager.m
//  Pods
//
//

#import "FLDownloadManager.h"
#import "FLMD5Helper.h"
#import "TCBlobDownloadManager.h"

@interface FLDownloadManager ()<TCBlobDownloaderDelegate>

/// 正在下载的所有的， 下载完成后移除。
@property(nonatomic, strong)NSMutableArray <TCBlobDownloader *>*downloadingDownloader;
@end

@implementation FLDownloadManager

- (instancetype)init{
    self = [super init];
    if (self) {
        self.downloadingDownloader = [NSMutableArray array];
    }
    return self;
}

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static id sharedManager = nil;
    dispatch_once(&onceToken, ^{
        sharedManager = [[[self class] alloc] init];
    });
    return sharedManager;
}
#pragma mark -TCBlobDownloaderDelegate
- (void)download:(TCBlobDownloader *)blobDownload didFinishWithSuccess:(BOOL)downloadFinished atPath:(NSString *)pathToFile{
    [self.downloadingDownloader removeObject:blobDownload];
}

- (TCBlobDownloader *)startSafeDownloadWithURL:(NSURL *)url
                                    customPath:(NSString *)customPathOrNil
                                 firstResponse:(void (^)(NSURLResponse *response))firstResponseBlock
                                      progress:(void (^)(uint64_t receivedLength, uint64_t totalLength, NSInteger remainingTime, float progress))progressBlock
                                         error:(void (^)(NSError *error))errorBlock
                                      complete:(void (^)(BOOL downloadFinished, NSString *pathToFile))completeBlock{
    //检测是否正在下载
    NSInteger downloadingIdx = [self indexOfDownloadingWithUrl:url.absoluteString];
    if (downloadingIdx != -1 && downloadingIdx < (self.downloadingDownloader.count)) {
        TCBlobDownloader *downloader = self.downloadingDownloader[downloadingIdx];
        // TCBlobDownloader 调用cancel 没有 complete block和delegate回调
        [downloader cancel];
        [self.downloadingDownloader removeObject:downloader];
        NSLog(@"正在下载，已移除");
    }
    TCBlobDownloader *downloader = [[TCBlobDownloadManager sharedInstance] startDownloadWithURL:url customPath:customPathOrNil firstResponse:firstResponseBlock progress:progressBlock error:errorBlock complete:completeBlock];
    //TODO 外部重新赋值 delegate ，会导致 downloadingDownloader 不能清理，但不影响逻辑
    downloader.delegate = self;
    [self.downloadingDownloader addObject:downloader];
    return downloader;
}


- (NSInteger)indexOfDownloadingWithUrl:(NSString *)url{
    __block NSInteger index = -1;
    [self.downloadingDownloader enumerateObjectsUsingBlock:^(TCBlobDownloader * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.downloadURL.absoluteString isEqualToString:url]) {
            index = idx;
        }
    }];
    return index;
}

- (NSString *)dataPathWithUrlString:(NSString *)urlStr;{
    if (!urlStr || urlStr.length == 0) {
        return nil;
    }
    NSString *filePath = [[TCBlobDownloadManager sharedInstance].defaultDownloadPath stringByAppendingPathComponent:[FLMD5Helper getFileNameWithUrlString:urlStr]];
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        return filePath;
    }
    return nil;
}
@end
